<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="登录" />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="info.mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="info.code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button :loading="isLoading" loading-text="登录中..." round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data () {
    return {
      info: {
        mobile: '',
        code: ''
      },
      isLoading: false,

      rules: {
        mobile: [
          // required:必填  message：错误提示文案
          { required: true, message: '请填写手机号' },
          { pattern: /^1[2-9]\d{9}$/, message: '请输入正确的手机号' }
        ],
        code: [
          { required: true, message: '请填写验证码' },
          { pattern: /^\d{6}$/, message: '请填写6位数字验证码' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      // 当这个事件触发时，说明绝对校验都通过了，可以放心发请求
      // 本接口特点：登录成功正常返回，登录失败报错
      try {
        this.isLoading = true
        const res = await loginAPI(this.info)
        this.$store.commit('user/setToken', res.data)
        this.$toast.success('登录成功')
        // 要么跳转到原本想访问的页面
        if (this.$route.query.back) {
          // 例如this.$route.query.back是/layout/mine，那这里就是去/layout/mine
          this.$router.push(this.$route.query.back)
        } else {
        // 要么跳转到首页
          this.$router.push('/layout/home')
        }
      } catch {
        this.$toast.fail('验证码错误')
      } finally {
        // 不管成功或失败都停掉加载状态
        this.isLoading = false
      }
    }
  }
}
</script>

<style></style>
